var lastQuantity;

$(function (){

    //输入框得到焦点则保存修改前数据
    $('.quantity').on('focus', function () {
        lastQuantity = this.value;
    });
    //焦点离开输入框后更新数据
    $('.quantity').on('blur', function () {
        if (this.value != null && this.value != '') {
            if (this.value == '0') {
                document.getElementById('remove_'+this.name).click();
            } else {
                qtyChangedUpdate(this.name, this.value);
            }
        }
        else {
            this.value = lastQuantity;
        }
    });
    //输入数量时按键松开后替换非数字符号
    $('.quantity').on('keyup', function() {
        this.value = this.value.replace(/[^\d]/g,'');
    })
    $('.op_plus').on('click', plus);
    $('.op_minus').on('click', minus);

})


function plus() {
    var itemId = $(this).data('itemid');
    var tg = document.getElementById('quantity_'+itemId);
    var result = eval(tg.value + '+1');
    tg.value = result;
    /*
        按钮被点击后似乎会自动提交表单的样子,所以下面的语句不需要
        qtyChangedUpdate(tg);
     */
}

function minus() {
    var itemId = $(this).data('itemid');
    var tg = document.getElementById('quantity_'+itemId);
    var result = eval(tg.value + '-1');
    if (result == '0') {
        document.getElementById('remove_'+itemId).click();
    }
    else {
        tg.value = result;
    }
}

function qtyChangedUpdate(itemId, qty) {
    $.ajax({
        type    : 'GET',
        url     : 'http://localhost:8080/updateCart?qtyChangedItemId=' + itemId + '&changedQty=' + qty,
        success : function (data) {
            var val = data.split('_');
            //显示服务器返回的更改数值后的 Total Cost
            document.getElementById('totalCost_'+itemId).innerHTML = '$' + priceFmt(val[0]);
            document.getElementById('subTotal').innerHTML = 'Sub Total: $' + priceFmt(val[1]);
        },
        error   : function (msg) {
            console.log(msg)
        }
    })
}

function priceFmt(price) {
    var temp = price.split('.')[0];
    var result = '';
    var idx = temp.length - 1;
    var cnt = 0;
    while (idx >= 0) {
        result = temp.charAt(idx) + result;
        cnt++;
        if (cnt == 3 && idx != 0) {
            result = ',' + result;
            cnt = 0;
        }
        idx--;
    }
    result = result + '.' + price.split('.')[1];
    return result;
}